import hashlib
import sys
sys.path.append('../')
import time
from io import BytesIO
import os
import datetime
#from log import setup_custom_logger
from PIL import Image
import uuid
# 日志系统初始化
#_ONE_DAY_IN_SECONDS = 60 * 60 * 24
#LOG_DIR = './logfiles'
#file_name = str(datetime.datetime.now().strftime('%Y-%m-%d'))
#my_logger = setup_custom_logger(os.path.join(LOG_DIR, '%s.log' % file_name), log_level="INFO")

class checkIsValid(object):
    """
        \**
            检查输入是否正确，定义错误码

        \**
    """
    def __init__(self, uid) -> None:
        self.uid = uid
        self.request_id = str(uuid.uuid4())

    def get_infenc_md5(self, _time, token, key):
        
        """
            @param: _time 时间戳
            @param: token 
            @param: key 密钥
        """
        res ='uid=' + str(self.uid) + '&_time=' + str(_time) +  '&token=' + str(token) + '&_key=' + str(key)
        # 进行md5加密
        md5_str = hashlib.md5(res.encode(encoding='utf-8')).hexdigest()
        return md5_str
    
    def check_param_exist(self, token, _time, inf_enc):
        """
            @param: _time 时间戳
            @param: token 
            @param: key 密钥
        """
        if token is None:
            return{
            "Response": {
            "Error": {
                "Code": 50308,
                "Message": "TokenMissing"
            },
            "request_id": self.request_id
            }
        }
        elif _time is None:
            return{
            "Response": {
            "Error": {
                "Code": 50301,
                "Message": "TimestampMissing"
            },
            "request_id": self.request_id
            }
        }        
        elif inf_enc is None:
            return{
            "Response": {
            "Error": {
                "Code": 50300,
                "Message": "InfEncMissing"
            },
            "request_id": self.request_id
            }
        }
        elif self.uid is None:
            return{
            "Response": {
            "Error": {
                "Code": 50215,
                "Message": "UidEmpty"
            },
            "request_id": self.request_id
            }
        }
        else:
#            my_logger.info('获取校验参数成功！')
            return None

        

    def check_is_valid(self,app_token, token, timestamp, app_key, inf_enc):
        """
            @param: app_token 写死的app_token
            @param: token 需要校验的token
            @param: timestamp 时间戳
            @param: app_key 密钥
            @param: inf_enc 加密后的字符串
        """
        if app_token != token:
#            my_logger.error('请求出错[3003]')
            return  {
            "Response": {
            "Error": {
                "Code": 50305,
                "Message": "TokenValid"
            },
            "request_id": self.request_id
            }
        }
        
        if int(time.time())*1000 > int(timestamp)*1000 + 10000:
#            my_logger.error('请求出错[3002],请检查当前设备时间是否正确')
            return  {
            "Response": {
            "Error": {
                "Code": 50303,
                "Message": "TimestampExpired"
            },
            "request_id": self.request_id
            }
        }
        server_inf_enc = self.get_infenc_md5(timestamp, token, app_key)
        # print('inf_ev', inf_enc)
        # print('server', server_inf_enc)
        if inf_enc != server_inf_enc:
#            my_logger.error('请求出错[3004]')
            return  {
            "Response": {
            "Error": {
                "Code": 50306,
                "Message": "InfEncInvalid"
            },
            "request_id": self.request_id
            }
        }
        print('the post params are valid')
        return None
    
    def check_is_img(self, image):
        try:
            image_file = BytesIO(image)
            Image.open(image_file)
            return None
        except:
            return  {
            "Response": {
            "Error": {
                "Code": 50204,
                "Message": "ImageEmpty"
            },
            "request_id": self.request_id
            }
        }

    
    def check_img_size(self, size, image):
        """
            @param: size: Tuple 
            @param: image: ndarray
            校验图片是否符合输入规范
            
        """
        max_allowed_size = 10 * 1024 * 1024 # 10MB的大小限制
        width, height = size
        # 人像分辨率必须大于100*100,部分非常规图像或者人像占比过小可能会影响皮肤分割（美白）效果。
        # 模型max_size<10M, max_resolution: 5000*5000
        image_size = image.size[0] * image.size[1] * 3
        if image_size > max_allowed_size:
            return  {
            "Response": {
            "Error": {
                "Code": 50203,
                "Message": "ImageSizeLimited"
            },
            "request_id": self.request_id
            }
        }
        if int(width) < 100  or int(height) < 100 or int(width) > 5000 or int(height) > 5000:

            return  {
            "Response": {
            "Error": {
                "Code": 50216,
                "Message": "ImageSizeTooLittle"
            },
            "request_id": self.request_id
            }
        }
        print('image size is valid')
        return None

        
# if __name__ == "__main__":
#     ch = checkIsValid()
#     x = tuple((1,43))
#     print(ch.check_img_size(x))

    
